package com.zhida.jiyangcenter.modle

import android.os.Bundle
import androidx.appcompat.widget.AppCompatImageView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.loadState.LoadService
import chooongg.base.loadState.LoadUtils
import chooongg.base.loadState.callback.EmptyCallback
import chooongg.base.loadState.callback.ErrorCallback
import chooongg.base.loadState.callback.NetworkCallback
import chooongg.base.utils.gone
import chooongg.base.utils.startActivity
import chooongg.base.utils.tipFail
import chooongg.base.utils.visible
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.zhida.jiyangcenter.DEFAULT_ROW
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.mian.fragment.MainShopItemFragment
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_comment_list.*
import me.zhanghai.android.materialratingbar.MaterialRatingBar
import java.math.RoundingMode

@TitleBar(false)
@ContentLayout(R.layout.activity_comment_list)
class CommentListActivity : BaseActivity() {
    val adapter = CommentAdapter()
    private var page = 1
    private lateinit var loadService: LoadService<*>
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.title("评论列表").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        loadService = LoadUtils.getDefault().register(refresh_layout) {
            page = 1
            getData()
        }
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context)
                .sizeResId(R.dimen.d10).colorResId(R.color.colorBack).build()
        )
        recycler_view.adapter = adapter
        refresh_layout.setOnRefreshListener {
            page = 1
            getData()
        }
        adapter.setPreLoadNumber(3)
        adapter.setOnLoadMoreListener({
            ++page
            getData()
        }, recycler_view)
        getData()
    }

    private fun getData() {
        lifecycleScope.request({
            if (intent.getStringExtra("kind") == "0") {
                APIShop.service().productCommentList(intent.getStringExtra("uuid"), page)
            } else {
                APIShop.service().serveCommentList(intent.getStringExtra("uuid"), page)
            }
        }, object : BaseAPI<CommentList>() {
            override fun onSuccess(t: CommentList?, state: Int, msg: String) {
                if (t != null && !t.comment.isNullOrEmpty()) {
                    if (page <= 1) {
                        adapter.setNewData(t.comment)
                        loadService.showSuccess()
                        refresh_layout.finishRefresh()
                        if (t.comment.size < DEFAULT_ROW) {
                            adapter.loadMoreEnd(true)
                        }
                    } else {
                        adapter.addData(t.comment)
                        if (t.comment.size < DEFAULT_ROW) {
                            adapter.loadMoreEnd(true)
                        } else adapter.loadMoreComplete()
                    }
                } else onError(APIException(APIException.Type.EMPTY))
            }

            override fun onError(e: APIException) {
                if (page <= 1) when (e.type) {
                    APIException.Type.EMPTY -> loadService.showCallback(
                        EmptyCallback::class,
                        "暂无商品"
                    )
                    APIException.Type.ERROR_NETWORK -> loadService.showCallback(NetworkCallback::class)
//                        APIException.Type.NOT_LOGIN -> loadService.showCallback(NotLoginCallback::class)
                    else -> loadService.showCallback(ErrorCallback::class, e.eMessage)
                } else when (e.type) {
                    APIException.Type.EMPTY -> {
                        adapter.loadMoreFail()
                    }
                    else -> adapter.loadMoreFail()
                }
            }

        })
    }

    class CommentAdapter :
        BaseQuickAdapter<CommentList.Comment, BaseViewHolder>(R.layout.item_seller_discuss) {
        override fun convert(helper: BaseViewHolder, item: CommentList.Comment?) {
            helper.setText(R.id.tv_name, item?.name)
                .setText(R.id.tv_content, item?.content)
                .setText(R.id.tv_time, item?.time)
            glideImage(
                helper.getView<AppCompatImageView>(R.id.iv_portrait), item?.avatar
                    ?: ""
            )
            val product_star = item?.describes!!.toFloat()
            val server_star = item.logistics!!.toFloat()
            val attitude = item.attitude!!.toFloat()
            val overallStar = ((product_star + server_star + attitude) / 3).toBigDecimal()
                .setScale(1, RoundingMode.HALF_UP).toFloat()
            helper.getView<MaterialRatingBar>(R.id.rating_bar).rating = overallStar
            val recyclerView = helper.getView<RecyclerView>(R.id.recycler_picture_view)
            if (recyclerView.layoutManager == null) {
                recyclerView.layoutManager = object : GridLayoutManager(mContext, 3) {
                    override fun canScrollVertically() = false
                }
            }
            if (item.picture.isNullOrEmpty()) {
                recyclerView.gone()
                recyclerView.adapter = null
            } else {
                recyclerView.visible()
                val adapter = PictureAdapter()
                adapter.bindToRecyclerView(recyclerView)
                adapter.setNewData(item.picture)
            }
        }

        /**
         * 评论图片适配器
         */
        private inner class PictureAdapter :
            BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_seller_discuss_picture) {
            override fun convert(helper: BaseViewHolder, item: String?) {
                val imageView = helper.getView<AppCompatImageView>(R.id.iv_image)
                glideImage(imageView, item ?: "", R.color.colorBack)
            }
        }
    }
}